package com.supersit.GZFDA.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.common.SysOSUtil;
import com.supersit.GZFDA.R;
import com.supersit.GZFDA.adapter.MyspinnerAdapter;
import com.supersit.GZFDA.app.StreetAndCommunity;
import com.supersit.GZFDA.db.DBUtils;
import com.supersit.GZFDA.db.GZFDASqliteDBHelper;
import com.supersit.GZFDA.db.LoadDBData;
import com.supersit.GZFDA.entity.Business;
import com.supersit.GZFDA.entity.UnUpLoad;
import com.supersit.GZFDA.receiver.NetworkConnection;
import com.supersit.GZFDA.util.AddressSearchData;
import com.supersit.GZFDA.util.AppManager;
import com.supersit.GZFDA.util.BaiDuMapUtils;
import com.supersit.GZFDA.util.BaiDuMapUtils.GetBaiduLocationResult;
import com.supersit.GZFDA.util.CustomDialog;
import com.supersit.GZFDA.util.FileUtils;
import com.supersit.GZFDA.util.NetUtils;
import com.supersit.GZFDA.util.ShowWindows;
import com.supersit.GZFDA.util.ShowWindows.Callback;
import com.supersit.GZFDA.view.ActionSheetDialog;
import com.supersit.GZFDA.view.ActionSheetDialog.OnSheetItemClickListener;
import com.zhy.autolayout.AutoLayoutActivity;

public class MainActivity extends AutoLayoutActivity implements TextWatcher,
		Callback, GetBaiduLocationResult {
	private TextView tv_date, tv_address, tv_oprate_address, tv_license_key,
			tv_community_name, tv_street_name, tv_keyType_name, tvLatitude,
			tvLongitude;
	private AutoCompleteTextView act_autoComplete;
	private CheckBox isAdd, not_data;
	// private ImageButton ib_more;/
	private LinearLayout llBack;
	// private EditText et_by;
	private Button btn_upload;
	private String flag;
	private ImageView iv_camer, community_pull_down, street_pull_down,
			keyType_pull_down;
	private SimpleDateFormat sdf;
	private SharedPreferences sp;
	private Context context;
	private String x, y, by, business_name, upload_date, username;
	private static String filePathx = "";
	private int[] photos = new int[] { R.id.iv_photo1, R.id.iv_photo2,
			R.id.iv_photo3, R.id.iv_photo4, R.id.iv_photo5, R.id.iv_photo6,
			R.id.iv_photo7, R.id.iv_photo8, R.id.iv_photo9 };

	String[] columns = new String[] { "_id", "business_name", "license_key" };
	SQLiteDatabase db;
	private ProgressDialog pd;
	private UnUpLoad unUpLoad;
	NetworkConnection networkConnection;
	private static int photoNum = 0;
	private static boolean isDelete;
	private List<ImageView> ivList;
	private String photoPath = "", manualMode = "0";// 坐标获取模式 0自动 1手动；
	private Business business;
	private String streetStr = "", photosType = "食品流通", business_type, key;
	private RadioGroup rg_photo_type;
	private RadioButton rb_type_key, rb_type_locale;
	private UnUpLoad u;
	private final int MapRequest = 88;
	private BaiDuMapUtils baiDuMapUtils;
	private String area = "番禺区";
	private boolean isManualpositioning = false;

	// Spinner
	private LinearLayout streetLayout;
	private ListView streetListView;
	private PopupWindow streetpopupWindow;
	private LinearLayout street_spinnerlayout;
	private ArrayList<String> streetList;
	private MyspinnerAdapter streetAdapter;
	private LinearLayout communityLayout;
	private PopupWindow communityPopupwindow;
	private ListView communityListView;
	private LinearLayout community_spinnerlayout;
	private ArrayList<String> communityList;
	private MyspinnerAdapter communityAdapter;
	private LinearLayout keyTypeLayout;
	private ListView keyTypeListView;
	private PopupWindow keyTypepopupWindow;
	private LinearLayout keyType_spinnerlayout;
	private ArrayList<String> keyTypeList;
	private MyspinnerAdapter keyTypeAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		context = this;
		AppManager.getAppManager().addActivity(MainActivity.this);
		sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		sp = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
		upload_date = sdf.format(new Date()).toString();
		username = sp.getString("USER_NAME", "");
		db = LoadDBData.openDatabase(context);
		initView();
		filePathx = FileUtils.makeDirs("temp");
		FileUtils.delAllFile(filePathx);
		ivList = new ArrayList<ImageView>();
		baiDuMapUtils = new BaiDuMapUtils(this, context, 0);
		// 开始定位
		baiDuMapUtils.startListener();
		binaData();
		// 注册后台自动上传广播
		// networkConnection = new NetworkConnection();
		// IntentFilter filter = new IntentFilter(
		// "android.net.conn.CONNECTIVITY_CHANGE");
		// registerReceiver(networkConnection, filter);
		pd = ProgressDialog.show(context, "定位", "正在定位中...");
	}

	private void binaData() {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			String type = bundle.getString("type");
			if ("business".equals(type)) {
				business = (Business) bundle.getSerializable("Business");
				if (business != null) {
					business_type = business.getBusiness_type();
					key = business.getLicense_key();
					act_autoComplete.setText(business.getBusiness_name());
					act_autoComplete.setEnabled(false);
					tv_oprate_address.setText(business.getOperate_addrress());
					tv_license_key.setText(business.getLicense_key());
					isAdd.setChecked(false);
					// CursorAdapter
					MyCursorAdpter adpter = new MyCursorAdpter(context, null, 1);
					// 设置适配器
					act_autoComplete.setAdapter(adpter);
				} else {
					Toast.makeText(context, "数据异常", 1).show();
				}
			} else if ("UnUpLoad".equals(type)) {
				u = (UnUpLoad) bundle.getSerializable("UnUpLoad");
				flag = bundle.getString("flag");
				String by = bundle.getString("by");
				if ("0".equals(by)) {
					business = DBUtils.getBusiness(u.getQYMC(), context);
					business_type = business.getBusiness_type();
					key = business.getLicense_key();
					act_autoComplete.setText(business.getBusiness_name());
					act_autoComplete.setEnabled(false);
					tv_oprate_address.setText(business.getOperate_addrress());
					tv_license_key.setText(business.getLicense_key());
					isAdd.setChecked(false);
					showPhotos(u.getPhotos());
				} else {
					business = DBUtils.getBusiness(u.getQYMC(), context);
					if (business == null) {
						act_autoComplete.setText(u.getQYMC());
						act_autoComplete.setEnabled(false);
					} else {
						key = business.getLicense_key();
						act_autoComplete.setText(business.getBusiness_name());
						act_autoComplete.setEnabled(false);
						tv_oprate_address.setText(business
								.getOperate_addrress());
						not_data.setChecked(true);
						tvLongitude.setText(String.format(
								getString(R.string.longitude), u.getX()));
						tvLatitude.setText(String.format(
								getString(R.string.latitude), u.getX()));

						tv_street_name.setText(u.getStreet());
						tv_community_name.setText(u.getCommunity());
						// tv_date.setText(u.getCJSJ() + "/" + u.getCJR());

					}

				}
			}
		} else {
			business_type = "未设定";
			key = "未收集";
			isAdd.setChecked(true);
			isAdd.setEnabled(false);
		}
		keyTypeList = new ArrayList<String>();
		keyTypeList.add("食品流通");
		keyTypeList.add("餐饮服务");
		keyTypeList.add("器械经营");
		keyTypeAdapter = new MyspinnerAdapter(this, keyTypeList);
		tv_keyType_name.setText(keyTypeAdapter.getList().get(0));
		keyType_spinnerlayout = (LinearLayout) findViewById(R.id.spn_key_type);
		keyType_spinnerlayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (keyTypeList.size() > 0) {
					keyType_spinnerlayout
							.setBackgroundResource(R.drawable.preference_first_item);
				}
				showWindow(keyType_spinnerlayout, tv_keyType_name, 2);

			}
		});

		streetList = StreetAndCommunity.getStreet(area);
		streetAdapter = new MyspinnerAdapter(this, streetList);
		tv_street_name.setText("请选择");
		ArrayList<String> arr = StreetAndCommunity.getCommunity(area,
				streetAdapter.getList().get(0));
		if (arr.size() > 0) {
			tv_community_name.setText("请选择");
		} else {
			tv_community_name.setText("无");
		}
		street_spinnerlayout = (LinearLayout) findViewById(R.id.spn_street);
		// ����Ҳఴť������������
		street_spinnerlayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (streetList.size() > 0) {
					street_spinnerlayout
							.setBackgroundResource(R.drawable.preference_first_item);
				}
				showWindow(street_spinnerlayout, tv_street_name, 0);

			}
		});

		tv_street_name.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				streetStr = tv_street_name.getText().toString();
				communityList = StreetAndCommunity
						.getCommunity(area, streetStr);
				communityAdapter = new MyspinnerAdapter(context, communityList);
				if (communityList.size() > 0) {
					tv_community_name.setText(communityList.get(0));
				} else {
					tv_community_name.setText("无");
				}
				// tv_community_name.setText(communityAdapter.getList().get(0));
				community_spinnerlayout = (LinearLayout) findViewById(R.id.spn_community);
				// ����Ҳఴť������������
				community_spinnerlayout
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {

								if (communityList.size() > 0) {
									community_spinnerlayout
											.setBackgroundResource(R.drawable.preference_first_item);
								}

								showWindow(community_spinnerlayout,
										tv_community_name, 1);

							}
						});
			}
		});

	}

	private void initView() {
		// iv_back = (ImageButton) findViewById(R.id.iv_back);
		llBack = (LinearLayout) findViewById(R.id.ll_main_back);
		// tv_cx = (TextView) findViewById(R.id.tv_unupload);
		tv_date = (TextView) findViewById(R.id.tv_date);
		tv_address = (TextView) findViewById(R.id.tv_address);
		act_autoComplete = (AutoCompleteTextView) findViewById(R.id.act_autoComplete);
		// 设置最少一个就开始匹配
		act_autoComplete.setThreshold(1);
		// et_by = (EditText) findViewById(R.id.et_by);
		btn_upload = (Button) findViewById(R.id.btn_upload);
		tv_date.setText(upload_date + "/" + username);
		iv_camer = (ImageView) findViewById(R.id.iv_camer);
		tv_oprate_address = (TextView) findViewById(R.id.tv_oprate_address);
		tv_license_key = (TextView) findViewById(R.id.tv_license_key);
		isAdd = (CheckBox) findViewById(R.id.checkBox1);
		isAdd.setChecked(true);
		isAdd.setEnabled(false);
		// ib_more = (ImageButton) findViewById(R.id.ib_more);
		// ib_more.setVisibility(View.GONE);
		not_data = (CheckBox) findViewById(R.id.cb_not_data);
		keyType_pull_down = (ImageView) findViewById(R.id.key_pull_down);
		tv_keyType_name = (TextView) findViewById(R.id.tv_key_type_name);

		community_pull_down = (ImageView) findViewById(R.id.community_pull_down);
		tv_street_name = (TextView) findViewById(R.id.tv_street_name);
		street_pull_down = (ImageView) findViewById(R.id.street_pull_down);
		tv_community_name = (TextView) findViewById(R.id.tv_community_name);
		rg_photo_type = (RadioGroup) findViewById(R.id.rg_photo_type);
		tvLatitude = (TextView) findViewById(R.id.tv_latitude);
		tvLongitude = (TextView) findViewById(R.id.tv_longitude);
		rb_type_key = (RadioButton) findViewById(R.id.rb_photo_key);
		rb_type_locale = (RadioButton) findViewById(R.id.rb_photo_site);
		bindListener();

	}

	private void bindListener() {
		// iv_back.setOnClickListener(onClickListener);
		llBack.setOnClickListener(onClickListener);
		btn_upload.setOnClickListener(onClickListener);
		// ib_more.setOnClickListener(onClickListener);
		// tv_cx.setOnClickListener(onClickListener);
		iv_camer.setOnClickListener(onClickListener);
		tv_address.setOnClickListener(onClickListener);
		act_autoComplete.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				String name = (String) view.getTag();
				String license_key = "";
				String operate_address = "";
				Cursor cursor = db.rawQuery(
						"select * from gzfad_data where business_name=?",
						new String[] { name });
				while (cursor.moveToNext()) {
					license_key = cursor.getString(cursor
							.getColumnIndex("license_key"));
					operate_address = cursor.getString(cursor
							.getColumnIndex("operate_address"));
				}
				if (!TextUtils.isEmpty(license_key)) {
					tv_license_key.setText(license_key);
				}
				if (!TextUtils.isEmpty(operate_address)) {
					tv_oprate_address.setText(operate_address);
				}
				isAdd.setChecked(false);
				cursor.close();
				// db.close();
			}
		});
		act_autoComplete.addTextChangedListener(this);
		final RadioButton rb_photo_key = (RadioButton) findViewById(R.id.rb_photo_key);
		final RadioButton rb_photo_site = (RadioButton) findViewById(R.id.rb_photo_site);

		rg_photo_type.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				// TODO Auto-generated method stub
				if (arg1 == rb_photo_key.getId()) {
					keyType_spinnerlayout.setVisibility(View.VISIBLE);
				} else if (arg1 == rb_photo_site.getId()) {
					keyType_spinnerlayout.setVisibility(View.GONE);
					photosType = "现场";
				}
			}
		});
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			switch (arg0.getId()) {
			case R.id.btn_upload:
				final String street = tv_street_name.getText().toString();
				final String community = tv_community_name.getText().toString();
				if (not_data.isChecked()) {
					final CustomDialog.Builder builder = new CustomDialog.Builder(
							context);
					View view = LayoutInflater.from(context).inflate(
							R.layout.dialog_radiogroup, null);
					RadioGroup rg = (RadioGroup) view
							.findViewById(R.id.rg_other);
					final RadioButton rb_0 = (RadioButton) view
							.findViewById(R.id.btn_0);
					final RadioButton rb_1 = (RadioButton) view
							.findViewById(R.id.btn_1);
					final RadioButton rb_2 = (RadioButton) view
							.findViewById(R.id.btn_2);

					rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(RadioGroup arg0, int arg1) {
							// TODO Auto-generated method stub
							builder.dialogDismiss();
							if (arg1 == rb_0.getId()) {
								by = "歇业";
							} else if (arg1 == rb_1.getId()) {
								by = "未营业";
							} else if (arg1 == rb_2.getId()) {
								by = "拒不配合";
							}

							business_name = act_autoComplete.getText()
									.toString();
							if (TextUtils.isEmpty(x)) {
								Toast.makeText(context, "x坐标导常",
										Toast.LENGTH_SHORT).show();
								return;
							}
							if (TextUtils.isEmpty(y)) {
								Toast.makeText(context, "y坐标异常",
										Toast.LENGTH_SHORT).show();
								return;
							}
							if (TextUtils.isEmpty(business_name)) {
								Toast.makeText(context, "企业名称不能为空",
										Toast.LENGTH_SHORT).show();
								return;
							}
							if ("请选择".equals(street)) {
								Toast.makeText(context, "请选择所在街道社区",
										Toast.LENGTH_SHORT).show();
								return;
							}
							upLoad(business_name, x, y, username, upload_date,
									by, business_name, street, community,
									manualMode);
						}
					});

					builder.setTitle("请选择原因");
					builder.setContentView(view);
					builder.create().show();
				} else {
					by = "0";
					business_name = act_autoComplete.getText().toString();
					if (TextUtils.isEmpty(x)) {
						Toast.makeText(context, "x坐标导常", Toast.LENGTH_SHORT)
								.show();
						return;
					}
					if (TextUtils.isEmpty(y)) {
						Toast.makeText(context, "y坐标异常", Toast.LENGTH_SHORT)
								.show();
						return;
					}
					if (TextUtils.isEmpty(business_name)) {
						Toast.makeText(context, "企业名称不能为空", Toast.LENGTH_SHORT)
								.show();
						return;
					}
					if (photoNum == 0) {
						Toast.makeText(context, "没有照相采集", Toast.LENGTH_SHORT)
								.show();
						return;
					}
					if ("请选择".equals(street)) {
						Toast.makeText(context, "请选择所在街道社区", Toast.LENGTH_SHORT)
								.show();
						return;
					}
					upLoad(business_name, x, y, username, upload_date, by,
							business_name, street, community, manualMode);

				}
				break;
			case R.id.ll_main_back:
				AppManager.getAppManager().finishActivity();
				break;
			// case R.id.ib_more:
			// ShowWindows sw = new ShowWindows(context, MainActivity.this);
			// sw.showPopupWindow(ib_more);
			//
			// // Intent intent = new Intent(context, UpLoadActivity.class);
			// // startActivity(intent);
			// break;
			case R.id.iv_camer:
				if (TextUtils.isEmpty(flag)) {
					if (!TextUtils.isEmpty(act_autoComplete.getText()
							.toString())) {

						if (rg_photo_type.getCheckedRadioButtonId() != -1) {
							if (photoNum < 9) {
								showPhotoWindow();
							} else {
								Toast.makeText(context, "最多只能有9张相片", 1).show();
							}
						} else {
							Toast.makeText(context, "请先选择照片类型", 1).show();
						}
					} else {
						Toast.makeText(context, "企业名称不能为空", 1).show();
					}
				} else {
					CustomDialog.Builder builder = new CustomDialog.Builder(
							MainActivity.this);
					builder.setMessage("确定要重新采集吗？如果重新采集原来采集的将会被清除！");
					builder.setTitle("提示");
					builder.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();

									int isDelete = DBUtils.deleteUnUpLoad(
											u.getQYMC(), context);
									if (isDelete != 0) {
										String[] temp = u.getPhotos()
												.split(",");
										File file = new File(temp[0]);
										String path = file.getParentFile()
												.getAbsolutePath();
										FileUtils.delFolder(path);
										for (int i = 0; i < ivList.size(); i++) {
											ivList.get(i).setVisibility(
													View.GONE);
										}
										ivList.clear();
										showPhotoWindow();
										flag = "";
									} else {
										Toast.makeText(context, "重新采集失败",
												Toast.LENGTH_SHORT).show();
										startActivity(new Intent(context,
												UpLoadActivity.class));
										AppManager.getAppManager()
												.finishActivity();
									}

								}
							});

					builder.setNegativeButton(
							"取消",
							new android.content.DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							});

					builder.create().show();

				}
				break;
			case R.id.tv_address:
				Intent mapIntent = new Intent(MainActivity.this,
						BaiDuMapActivity.class);
				mapIntent.putExtra("x", x);
				mapIntent.putExtra("y", y);
				// tv_address.setText("");
				// mLocationClient.requestLocation();// 刷新定位
				startActivityForResult(mapIntent, MapRequest);
				isManualpositioning = true;

				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		baiDuMapUtils.stopListener();
		baiDuMapUtils.unRegisterLocationListener();
		// unregisterReceiver(networkConnection);// 销毁广播
	}

	/**
	 * 自动补全适配器
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyCursorAdpter extends CursorAdapter {
		private int columnIndex;

		public MyCursorAdpter(Context context, Cursor c, int col) {
			super(context, c);
			this.columnIndex = col;
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			final LayoutInflater inflater = LayoutInflater.from(context);
			final View view = inflater.inflate(
					R.layout.autocompletetextview_item, null);
			TextView tv = (TextView) view
					.findViewById(R.id.tv_autocompletetextview_item);
			tv.setTextSize(20);
			tv.setText(cursor.getString(columnIndex));
			tv.setTag(cursor.getString(columnIndex));
			return tv;
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			((TextView) view).setText(cursor.getString(columnIndex));
		}

		@Override
		public String convertToString(Cursor cursor) {
			String data = cursor.getString(columnIndex);
			return data;
		}

		@Override
		public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
			if (constraint != null) {
				String selection = "business_name like \'%"
						+ constraint.toString() + "%\' order by id limit 5";
				return db.query("gzfad_data", columns, selection, null, null,
						null, null);
			} else {
				return null;
			}
		}
	}

	private void upLoad(String QYMC, String X, String Y, String CJR,
			String CJSJ, String BZ, String bubusiness_name, String street,
			String community, String manualMode) {
		unUpLoad = new UnUpLoad();
		unUpLoad.setBZ(BZ);
		unUpLoad.setCJR(CJR);
		unUpLoad.setCJSJ(CJSJ);
		unUpLoad.setQYMC(QYMC);
		unUpLoad.setX(X);
		unUpLoad.setY(Y);
		unUpLoad.setStreet(street);
		unUpLoad.setCommunity(community);
		unUpLoad.setManualMode(manualMode);

		String toDir = FileUtils.makeDirs(street+"_"+QYMC);
		// 重命名文件夹
		FileUtils.renameDirectory(filePathx, toDir);

		// // 重命名文件夹
		// String saveFile = FileUtils.makeDirs(unUpLoad.getQYMC());
		// // 把temp的文件夹剪切到新的文件夹
		// FileUtils.cutGeneralFile(filePathx + "/", saveFile);
		// List<String> photoList = FileUtils.getFileNames(saveFile + "/temp/");

		List<String> photoList = FileUtils.getFileNames(toDir);

		GZFDASqliteDBHelper dbHelper = new GZFDASqliteDBHelper(context);
		ContentValues values = new ContentValues();
		StringBuffer sb = new StringBuffer();
		if (photoList != null) {
			for (int i = 0; i < photoList.size(); i++) {
				if (i != photoList.size() - 1) {
					sb.append(photoList.get(i) + ",");
				} else {
					sb.append(photoList.get(i));
				}
			}
		}
		values.put("photos", sb.toString());
		values.put("business_name", unUpLoad.getQYMC());
		values.put("uploaddate", unUpLoad.getCJSJ());
		values.put("upuser", unUpLoad.getCJR());
		values.put("coords_x", unUpLoad.getX());
		values.put("coords_y", unUpLoad.getY());
		values.put("by", unUpLoad.getBZ());
		values.put("isupload", "-1");
		values.put("street", unUpLoad.getStreet());
		values.put("community", unUpLoad.getCommunity());
		values.put("manualmode", unUpLoad.getManualMode());
		if (!DBUtils.isExist(QYMC, context)) {
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			db.beginTransaction();
			db.insert("unupload", null, values);
			db.setTransactionSuccessful();
			db.endTransaction();
			db.close();
		} else {
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			db.beginTransaction();
			db.update("unupload", values, "business_name=?",
					new String[] { QYMC });
			db.setTransactionSuccessful();
			db.endTransaction();
			db.close();
		}
		SQLiteDatabase db1 = LoadDBData.openDatabase(MainActivity.this);
		String sql = "update gzfad_data set is_upload = '-1' where business_name='"
				+ bubusiness_name + "'";
		// ContentValues valuesa = new ContentValues();
		// valuesa.put("is_upload", "-1");
		// db1.update("gzfad_data", valuesa, "business_name=?", new String[]
		// {});
		db1.execSQL(sql);
		db1.close();
		Toast.makeText(context, "保存成功", 1).show();
		act_autoComplete.setEnabled(true);
		act_autoComplete.setText("");
		for (int y = 0; y < photos.length; y++) {
			ImageView iv = (ImageView) findViewById(photos[y]);
			if (iv.getVisibility() == View.VISIBLE) {
				iv.setVisibility(View.GONE);
			}
		}
		// et_by.setText("");
		photoNum = 0;
		ivList.clear();
		AppManager.getAppManager().finishActivity();
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 100:
				pd.dismiss();
				Toast.makeText(context, "数据上传成功", Toast.LENGTH_SHORT).show();
				act_autoComplete.setText("");
				// et_by.setText("");
				FileUtils.makeDirs(unUpLoad.getQYMC());
				break;
			case -100:
				pd.dismiss();
				GZFDASqliteDBHelper dbHelper = new GZFDASqliteDBHelper(context);
				SQLiteDatabase db = dbHelper.getWritableDatabase();
				Cursor cursor = db.rawQuery(
						"select * from unupload where business_name=?",
						new String[] { unUpLoad.getQYMC() });
				if (cursor.moveToNext()) {
					db.execSQL("UPDATE unupload set uploaddate='"
							+ unUpLoad.getCJSJ() + "',upuser='"
							+ unUpLoad.getCJR() + "',coords_x ='"
							+ unUpLoad.getX() + "',coords_y='"
							+ unUpLoad.getY() + "',by='" + unUpLoad.getBZ()
							+ "' WHERE business_name='" + unUpLoad.getQYMC()
							+ "'");
				} else {
					String sql;
					if (!TextUtils.isEmpty(unUpLoad.getBZ())) {
						sql = "INSERT INTO unupload VALUES (null,'"
								+ unUpLoad.getQYMC() + "','"
								+ unUpLoad.getCJSJ() + "','"
								+ unUpLoad.getCJR() + "','" + unUpLoad.getX()
								+ "','" + unUpLoad.getY() + "','"
								+ unUpLoad.getBZ() + "','-1')";
					} else {
						sql = "INSERT INTO unupload VALUES (null,'"
								+ unUpLoad.getQYMC() + "','"
								+ unUpLoad.getCJSJ() + "','"
								+ unUpLoad.getCJR() + "','" + unUpLoad.getX()
								+ "','" + unUpLoad.getY() + "',null,'-1')";
					}

					db.execSQL(sql);
					cursor.close();
					db.close();
				}
				Toast.makeText(context, "服务器异常，数据上传失败，已存至本地，下次打开程序将会自动上传",
						Toast.LENGTH_SHORT).show();
				act_autoComplete.setText("");
				// et_by.setText("");

				break;
			case -200:
				pd.dismiss();
				Toast.makeText(context,
						"对象：“" + unUpLoad.getQYMC() + "”此条数据已经上传处理",
						Toast.LENGTH_SHORT).show();
			default:
				break;
			}
		}

	};

	public void showMenuWindow() {
		new ActionSheetDialog(context)
				.builder()
				.setCancelable(false)
				.setCanceledOnTouchOutside(true)
				.addSheetItem("密码修改", ActionSheetDialog.SheetItemColor.Blue,
						new OnSheetItemClickListener() {

							@Override
							public void onClick(int which) {
								// TODO Auto-generated method stub
								Intent intent = new Intent(context,
										UpdatePwd.class);
								startActivity(intent);
							}
						})
				.addSheetItem("清理缓存", ActionSheetDialog.SheetItemColor.Blue,
						new OnSheetItemClickListener() {

							@Override
							public void onClick(int which) {
								// TODO Auto-generated method stub
								// 获取根目录
								String SDCardRoot = Environment
										.getExternalStorageDirectory()
										.getAbsolutePath();
								// 获取文件夹目录
								final String fileDir = SDCardRoot
										+ File.separator + "GZFAD"
										+ File.separator;

								new AlertDialog.Builder(context)
										.setTitle("警告")
										.setMessage(
												"清理缓存可能导致有用的数据丢失,请确认已经上传所有采集数据！")
										.setPositiveButton(
												"确定清理",
												new DialogInterface.OnClickListener() {

													@Override
													public void onClick(
															DialogInterface arg0,
															int arg1) {
														// TODO Auto-generated
														// method stub
														isDelete = FileUtils
																.delAllFile(fileDir);
														if (isDelete) {
															Toast.makeText(
																	context,
																	"数据请理完毕", 1)
																	.show();
															isDelete = false;
														} else {
															Toast.makeText(
																	context,
																	"清理失败", 1)
																	.show();
														}
														arg0.dismiss();
													}
												})
										.setNegativeButton(
												"取消",
												new DialogInterface.OnClickListener() {

													@Override
													public void onClick(
															DialogInterface arg0,
															int arg1) {
														// TODO Auto-generated
														// method stub
														arg0.dismiss();
													}
												}).show();

							}
						}).show();
	}

	public void showPhotoWindow() {
		new ActionSheetDialog(context)
				.builder()
				.setCancelable(false)
				.setCanceledOnTouchOutside(true)
				.addSheetItem("打开相机", ActionSheetDialog.SheetItemColor.Blue,
						new OnSheetItemClickListener() {

							@Override
							public void onClick(int which) {
								if (!TextUtils.isEmpty(filePathx)) {
									photograph();
								}

							}
						})
				.addSheetItem("相册选取", ActionSheetDialog.SheetItemColor.Blue,
						new OnSheetItemClickListener() {

							@Override
							public void onClick(int which) {
								// TODO Auto-generated method stub
								// 打开本地相册
								Intent intent = new Intent(Intent.ACTION_PICK);
								intent.setType("image/*");// 相片类型
								startActivityForResult(intent, 200);
							}
						}).show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		showMenuWindow();
		return false;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		// 类别-企业名称-证书编号-中文描述.png
		// 1.分隔符“-”必须使用英文输入法下的“-”;
		// 2 “类别”，“企业名称”，“证书编号”，”中文描述“中不允许出现横杠（-），空格等特殊字符;
		// 3 类别必须为（食品经营、食品流通、餐饮服务、器械经营）其中一个
		// 4 中文描述若为证书照片则为“证书”；若为现场环境照片则为：“现场”，其他以此类推。
		// if ("食品流通".equals(photosType)) {
		// photosType = "0";
		// } else if ("餐饮服务".equals(photosType)) {
		// photosType = "1";
		// } else if ("器械经营".equals(photosType)) {
		// photosType = "2";
		// } else if ("现场".equals(photosType)) {
		// photosType = "3";
		// }
		String businessName = act_autoComplete.getText().toString().trim();
		String businessType = business == null ? "未设定" : business
				.getBusiness_type();
		String businessKey = business == null ? "无" : business.getLicense_key();
		if (requestCode == 100) {
			if (data == null) {
				photoPath = Environment.getExternalStorageDirectory()
						+ "/image.jpg";
				if (new File(photoPath).exists()) {// 如果文件存在
					if (!TextUtils.isEmpty(photoPath.trim())) {
						// 类别-企业名称-证书编号-中文描述.png
						String name = String
								.valueOf(System.currentTimeMillis());
						String photoName = businessType + "_" + businessName
								+ "_" + businessKey + "_" + photosType + "_"
								+ name + ".jpg";
						String copyPhotoPath = filePathx + File.separator
								+ photoName;
						Log.d("tag", copyPhotoPath);
						File fromFile = new File(photoPath);
						File toFile = new File(copyPhotoPath);
						FileUtils.copyfile(fromFile, toFile, true);
						BitmapFactory.Options options = new BitmapFactory.Options();
						// 如果inJustDecoedBounds设置为true的话，解码bitmap时可以只返回其高、宽和Mime类型，而不必为其申请内存，从而节省了内存空间。
						options.inJustDecodeBounds = true;
						Bitmap bitmap = BitmapFactory.decodeFile(copyPhotoPath);
						options.inJustDecodeBounds = false;
						Bitmap bm = ThumbnailUtils.extractThumbnail(bitmap, 60,
								60);
						if (bitmap != null)
							bitmap.recycle();

						try {
							final List<String> photoPaths = FileUtils
									.getFileNames(filePathx + File.separator);
							photoNum = photoPaths.size();
							for (int i = 0; i < photoNum; i++) {
								ImageView iv = (ImageView) findViewById(photos[i]);
								if (iv.getVisibility() == View.GONE) {
									iv.setVisibility(View.VISIBLE);
									iv.setImageBitmap(bm);
									// bm.recycle();
									iv.setTag(i);
									iv.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View arg0) {
											// TODO Auto-generated method stub
											int x = (Integer) arg0.getTag();
											File file = new File(photoPaths
													.get(x));
											Intent it = new Intent(
													Intent.ACTION_VIEW);
											Uri mUri = Uri.parse("file://"
													+ file.getPath());
											it.setDataAndType(mUri, "image/*");
											startActivityForResult(it, 300);
										}
									});
									ivList.add(iv);

									break;
								}
							}
						} catch (Exception e) {
							Log.e("error", e.getMessage());
						}
					}
					FileUtils.deleteGeneralFile(photoPath);
					rg_photo_type.clearCheck();
				}
			}
		} else if (requestCode == 200) {
			if (data != null) {
				Uri uri = data.getData();
				if (null != uri) {
					photoPath = getRealFilePath(context, uri);
					String name = String.valueOf(System.currentTimeMillis());
					String photoName = businessType + "_" + businessName + "_"
							+ businessKey + "_" + photosType + "_" + name
							+ ".jpg";
					String copyPhotoPath = filePathx + File.separator
							+ photoName;
					Log.d("tag", copyPhotoPath);
					File fromFile = new File(photoPath);
					File toFile = new File(copyPhotoPath);
					FileUtils.copyfile(fromFile, toFile, true);
					BitmapFactory.Options options = new BitmapFactory.Options();
					// 如果inJustDecoedBounds设置为true的话，解码bitmap时可以只返回其高、宽和Mime类型，而不必为其申请内存，从而节省了内存空间。
					options.inJustDecodeBounds = true;
					Bitmap bitmap = BitmapFactory.decodeFile(copyPhotoPath);
					options.inJustDecodeBounds = false;
					Bitmap bm = ThumbnailUtils.extractThumbnail(bitmap, 60, 60);
					bitmap.recycle();
					try {
						final List<String> photoPaths = FileUtils
								.getFileNames(filePathx + File.separator);
						photoNum = photoPaths.size();
						for (int i = 0; i < photoNum; i++) {
							ImageView iv = (ImageView) findViewById(photos[i]);
							if (iv.getVisibility() == View.GONE) {
								iv.setVisibility(View.VISIBLE);
								iv.setImageBitmap(bm);
								// bm.recycle();
								iv.setTag(i);
								iv.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View arg0) {
										// TODO Auto-generated method stub
										int x = (Integer) arg0.getTag();
										File file = new File(photoPaths.get(x));
										Intent it = new Intent(
												Intent.ACTION_VIEW);
										Uri mUri = Uri.parse("file://"
												+ file.getPath());
										it.setDataAndType(mUri, "image/*");
										startActivityForResult(it, 300);
									}
								});
								ivList.add(iv);
								break;
							}
						}
					} catch (Exception e) {
						Log.e("error", e.getMessage());
					} finally {
						rg_photo_type.clearCheck();
					}
				}
			}
		} else if (requestCode == 300) {
			// 隐藏所有控件
			for (int i = 0; i < ivList.size(); i++) {
				ivList.get(i).setVisibility(View.GONE);
			}
			ivList.clear();
			final List<String> photoPaths = FileUtils.getFileNames(filePathx
					+ File.separator);
			for (int y = 0; y < photoPaths.size(); y++) {
				Bitmap bitmap = BitmapFactory.decodeFile(photoPaths.get(y));
				// 获取缩略图
				Bitmap bm = ThumbnailUtils.extractThumbnail(bitmap, 60, 60);
				bitmap.recycle();
				ImageView iv = (ImageView) findViewById(photos[y]);
				if (iv.getVisibility() == View.GONE) {
					iv.setVisibility(View.VISIBLE);
					iv.setImageBitmap(bm);
					// bm.recycle();
					iv.setTag(y);
					iv.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							int x = (Integer) arg0.getTag();
							File file = new File(photoPaths.get(x));
							Intent it = new Intent(Intent.ACTION_VIEW);
							Uri mUri = Uri.parse("file://" + file.getPath());
							it.setDataAndType(mUri, "image/*");
							startActivityForResult(it, 300);
						}
					});
					ivList.add(iv);
				}

			}

		} else if (requestCode == MapRequest) {
			if (null != data) {
				double lat = data.getDoubleExtra("lat", 0);
				double lng = data.getDoubleExtra("lng", 0);
				String address = data.getStringExtra("address");
				if ("null".equals(address) || lat <= 0 || lng <= 0) {
					y = "";
					x = "";
					tvLongitude.setText(String.format(
							getString(R.string.longitude), x));
					tvLatitude.setText(String.format(
							getString(R.string.latitude), y));
					tv_address.setText("定位失败  ,请查检网络!");
					Toast.makeText(context, "获取的坐标异常，请检查网络并重新获取定位",
							Toast.LENGTH_LONG).show();
				} else {
					y = lat + "";
					x = lng + "";
					tvLongitude.setText(String.format(
							getString(R.string.longitude), x));
					tvLatitude.setText(String.format(
							getString(R.string.latitude), y));
					tv_address.setText(address);
					manualMode = "1";
				}
			}
		}

	}

	/**
	 * 调用相机拍照
	 * 
	 * @param filePath
	 */
	private void photograph() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		Uri imageUri = Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), "image.jpg"));
		// 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(openCameraIntent, 100);
	}

	/**
	 * 根据URI获取图片的路径
	 * 
	 * @param context
	 * @param uri
	 * @return
	 */
	public static String getRealFilePath(final Context context, final Uri uri) {
		if (null == uri)
			return null;
		final String scheme = uri.getScheme();
		String data = null;
		if (scheme == null)
			data = uri.getPath();
		else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
			data = uri.getPath();
		} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
			Cursor cursor = context.getContentResolver().query(uri,
					new String[] { ImageColumns.DATA }, null, null, null);
			if (null != cursor) {
				if (cursor.moveToFirst()) {
					int index = cursor.getColumnIndex(ImageColumns.DATA);
					if (index > -1) {
						data = cursor.getString(index);
					}
				}
				cursor.close();
			}
		}
		return data;
	}

	@Override
	public void afterTextChanged(Editable arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		isAdd.setChecked(true);
		tv_license_key.setText("");
		tv_oprate_address.setText("");
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		switch (position) {
		case 0:
			Intent intent = new Intent(context, UpLoadActivity.class);
			startActivity(intent);
			break;
		case 1:
			View Dview = LayoutInflater.from(context).inflate(
					R.layout.activity_fuzzy_search, null);
			final EditText et_search = (EditText) Dview
					.findViewById(R.id.et_fuzzy_search);
			CustomDialog.Builder builder = new CustomDialog.Builder(this);
			// builder.setMessage("这个就是自定义的提示框");
			builder.setTitle("街道搜索");
			builder.setContentView(Dview);
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();

							if (!TextUtils.isEmpty(et_search.getText()
									.toString().trim())) {
								String argStr = et_search.getText().toString()
										.trim();
								Log.d("tag", "街道名称:" + argStr);
								AddressSearchData asd = new AddressSearchData(
										context);
								asd.getForResult(argStr);
							} else {
								Toast.makeText(context, "街道名称不能为空",
										Toast.LENGTH_SHORT).show();
							}
						}
					});

			builder.setNegativeButton("取消",
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});

			builder.create().show();
			break;
		default:
			break;
		}
	}

	// 返回键的重写
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			AppManager.getAppManager().finishActivity();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void showWindow(View position, final TextView txt, int spinnerNum) {
		if (0 == spinnerNum) {
			streetLayout = (LinearLayout) LayoutInflater.from(this).inflate(
					R.layout.street_dropdown, null);
			streetListView = (ListView) streetLayout
					.findViewById(R.id.listView);
			streetListView.setAdapter(streetAdapter);
			streetpopupWindow = new PopupWindow(position);
			// ���õ���Ŀ��Ϊ�����ļ��Ŀ�
			streetpopupWindow.setWidth(street_spinnerlayout.getWidth());
			streetpopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
			// ����һ��͸���ı�������Ȼ�޷�ʵ�ֵ�������⣬������ʧ
			streetpopupWindow.setBackgroundDrawable(new BitmapDrawable());
			// ���õ�������ⲿ��������ʧ
			streetpopupWindow.setOutsideTouchable(true);
			streetpopupWindow.setFocusable(true);
			streetpopupWindow.setContentView(streetLayout);
			// ���õ�����ֵ�λ�ã���v�����·�����ƫ��textview�Ŀ�ȣ�Ϊ�˶���~���᲻ƫ��
			streetpopupWindow.showAsDropDown(position, 0, 0);
			streetpopupWindow.setOnDismissListener(new OnDismissListener() {
				@Override
				public void onDismiss() {
					// TODO Auto-generated method stub
					street_spinnerlayout
							.setBackgroundResource(R.drawable.preference_single_item);
				}

			});
			// listView��item����¼�
			streetListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					txt.setText(streetList.get(arg2));// ������ѡ��item��Ϊ������ı���
					// ������ʧ
					streetpopupWindow.dismiss();
					streetpopupWindow = null;
				}
			});
		} else if (1 == spinnerNum) {

			communityLayout = (LinearLayout) LayoutInflater.from(this).inflate(
					R.layout.community_dropdown, null);
			communityListView = (ListView) communityLayout
					.findViewById(R.id.listView);
			communityListView.setAdapter(communityAdapter);
			communityPopupwindow = new PopupWindow(position);
			// ���õ���Ŀ��Ϊ�����ļ��Ŀ�
			communityPopupwindow.setWidth(community_spinnerlayout.getWidth());
			communityPopupwindow.setHeight(LayoutParams.WRAP_CONTENT);
			// ����һ��͸���ı�������Ȼ�޷�ʵ�ֵ�������⣬������ʧ
			communityPopupwindow.setBackgroundDrawable(new BitmapDrawable());
			// ���õ�������ⲿ��������ʧ
			communityPopupwindow.setOutsideTouchable(true);
			communityPopupwindow.setFocusable(true);
			communityPopupwindow.setContentView(communityLayout);
			// ���õ�����ֵ�λ�ã���v�����·�����ƫ��textview�Ŀ�ȣ�Ϊ�˶���~���᲻ƫ��
			communityPopupwindow.showAsDropDown(position, 0, 0);
			communityPopupwindow.setOnDismissListener(new OnDismissListener() {
				@Override
				public void onDismiss() {
					// TODO Auto-generated method stub
					community_spinnerlayout
							.setBackgroundResource(R.drawable.preference_single_item);
				}

			});
			// listView��item����¼�
			communityListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					txt.setText(communityList.get(arg2));// ������ѡ��item��Ϊ������ı���
					// ������ʧ
					communityPopupwindow.dismiss();
					communityPopupwindow = null;
				}
			});

		} else if (2 == spinnerNum) {

			keyTypeLayout = (LinearLayout) LayoutInflater.from(this).inflate(
					R.layout.keytype_dropdown, null);
			keyTypeListView = (ListView) keyTypeLayout
					.findViewById(R.id.listView);
			keyTypeListView.setAdapter(keyTypeAdapter);
			keyTypepopupWindow = new PopupWindow(position);
			// ���õ���Ŀ��Ϊ�����ļ��Ŀ�
			keyTypepopupWindow.setWidth(keyType_spinnerlayout.getWidth());
			keyTypepopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
			// ����һ��͸���ı�������Ȼ�޷�ʵ�ֵ�������⣬������ʧ
			keyTypepopupWindow.setBackgroundDrawable(new BitmapDrawable());
			// ���õ�������ⲿ��������ʧ
			keyTypepopupWindow.setOutsideTouchable(true);
			keyTypepopupWindow.setFocusable(true);
			keyTypepopupWindow.setContentView(keyTypeLayout);
			// ���õ�����ֵ�λ�ã���v�����·�����ƫ��textview�Ŀ�ȣ�Ϊ�˶���~���᲻ƫ��
			keyTypepopupWindow.showAsDropDown(position, 0, 0);
			keyTypepopupWindow.setOnDismissListener(new OnDismissListener() {
				@Override
				public void onDismiss() {
					// TODO Auto-generated method stub
					keyType_spinnerlayout
							.setBackgroundResource(R.drawable.preference_single_item);
				}

			});
			// listView��item����¼�
			keyTypeListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					txt.setText(keyTypeList.get(arg2));// ������ѡ��item��Ϊ������ı���
					photosType = keyTypeList.get(arg2);
					// ������ʧ
					keyTypepopupWindow.dismiss();
					keyTypepopupWindow = null;
				}
			});

		}

	}

	private void showPhotos(String photosPath) {
		// 隐藏所有控件
		for (int i = 0; i < ivList.size(); i++) {
			ivList.get(i).setVisibility(View.GONE);
		}
		ivList.clear();
		final String[] photoPaths = photosPath.split(",");
		// final List<String> photoPaths = FileUtils.getFileNames(filePathx
		// + File.separator);
		for (int y = 0; y < photoPaths.length; y++) {
			Bitmap bitmap = BitmapFactory.decodeFile(photoPaths[y]);
			// 获取缩略图
			Bitmap bm = ThumbnailUtils.extractThumbnail(bitmap, 60, 60);
			bitmap.recycle();
			ImageView iv = (ImageView) findViewById(photos[y]);
			if (iv.getVisibility() == View.GONE) {
				iv.setVisibility(View.VISIBLE);
				iv.setImageBitmap(bm);
				// bm.recycle();
				iv.setTag(y);
				iv.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						int x = (Integer) arg0.getTag();
						File file = new File(photoPaths[x]);
						Intent it = new Intent(Intent.ACTION_VIEW);
						Uri mUri = Uri.parse("file://" + file.getPath());
						it.setDataAndType(mUri, "image/*");
						startActivity(it);
					}
				});
				ivList.add(iv);
			}

		}

	}

	@Override
	public void onReceiveLocation(BDLocation location) {
		// TODO Auto-generated method stub
		if (isManualpositioning) {
			baiDuMapUtils.unRegisterLocationListener();
		} else {
			if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				pd.dismiss();
				x = location.getLongitude() + "";
				y = location.getLatitude() + "";
				String Province = location.getProvince();
				String City = location.getCity();
				String District = location.getDistrict();
				String Street = location.getStreet();
				String StreetNumber = location.getStreetNumber();
				tvLongitude.setText(String.format(
						getString(R.string.longitude), x));
				tvLatitude.setText(String.format(getString(R.string.latitude),
						y));
				tv_address.setText(Province + City + District + Street
						+ StreetNumber);
			} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
				pd.dismiss();
				tv_address.setText("定位失败  ,请查检网络!" + location.getLocType());
			} else if (location.getLocType() == BDLocation.TypeNone) {
				pd.dismiss();
				tv_address.setText("无效定位结果!" + location.getLocType());
			} else {
				pd.dismiss();
				tv_address.setText("定位失败!" + location.getLocType());
			}
		}

	}
}
